/**
 * 双指针（滑动窗口）
 * @param {string} s
 * @return {number}
 */
export var lengthOfLongestSubstring = function (s) {
  const map = new Map()
  let max = 0
  let left = 0
  for (let right = 0; right < s.length; right++) {
    if (map.has(s[right]) && map.get(s[right]) >= left) {
      left = map.get(s[right]) + 1
    }
    // 每次更新当前字符的位置到map, 并且更新最大值
    map.set(s[right], right)
    max = Math.max(max, right - left + 1)
  }
  return max
}

/**
 * @param {string} s
 * @return {number}
 */
export var lengthOfLongestSubstring2 = function (s) {
  if (s === '') {
    return 0
  }
  const collector = new Set()
  let rk = -1
  let res = 1
  for (let i = 0; i < s.length; i++) {
    if (res > s.length - i - 1) {
      break
    }
    if (i > 0) {
      collector.delete(s.charAt(i - 1))
    }
    while (rk + 1 < s.length && !collector.has(s.charAt(rk + 1))) {
      collector.add(s.charAt(rk + 1))
      rk++
    }
    res = Math.max(res, rk + 1 - i)
  }
  return res
}
